<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>{{ isEdit ? '编辑医生' : '新增医生' }}</h3>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px"
        label-position="right"
        status-icon
      >
        <el-divider content-position="left">基本信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="工号" prop="staffId">
              <el-input 
                v-model="form.staffId" 
                placeholder="请输入工号"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入医生姓名" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择性别" style="width: 100%">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="职称" prop="title">
              <el-select v-model="form.title" placeholder="请选择职称" style="width: 100%">
                <el-option label="主任医师" value="主任医师" />
                <el-option label="副主任医师" value="副主任医师" />
                <el-option label="主治医师" value="主治医师" />
                <el-option label="住院医师" value="住院医师" />
                <el-option label="医师" value="医师" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="所属科室" prop="departmentId">
              <el-select 
                v-model="form.departmentId" 
                placeholder="请选择科室" 
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="dept in departments"
                  :key="dept.value || dept.id || dept.departmentId || index"
                  :label="dept.label || dept.name"
                  :value="dept.value || dept.id || dept.departmentId || String(index)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="在职" value="在职" />
                <el-option label="离职" value="离职" />
                <el-option label="停诊" value="停诊" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="专长" prop="specialties">
              <el-select 
                v-model="form.specialties" 
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请输入专长，可多选"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">联系信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="手机号" prop="contactInfo.phone">
              <el-input 
                v-model="form.contactInfo.phone" 
                placeholder="请输入手机号"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="电子邮箱" prop="contactInfo.email">
              <el-input v-model="form.contactInfo.email" placeholder="请输入电子邮箱" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="办公室" prop="contactInfo.office">
              <el-input v-model="form.contactInfo.office" placeholder="请输入办公室位置" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">个人资料</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="个人简介" prop="biography">
              <el-input 
                v-model="form.biography" 
                type="textarea" 
                :rows="4" 
                placeholder="请输入医生个人简介"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="教育背景" prop="education">
              <el-select 
                v-model="form.education" 
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请输入教育背景，可多选"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="资格认证" prop="certifications">
              <el-select 
                v-model="form.certifications" 
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请输入资格认证，可多选"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="照片" prop="photo">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="handleAvatarUpload"
              >
                <img v-if="form.photo" :src="form.photo" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <el-input v-model="form.photo" placeholder="或输入图片URL" style="margin-top: 10px;" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { doctorAPI } from '@/utils/api'
import { formRules } from '@/utils/validate'
import { getDepartmentOptions } from '@/utils/formData'
import { normalizeId } from '@/utils/api'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const loading = ref(false)
const departments = ref([])

// 判断是新增还是编辑
const isEdit = computed(() => {
  return route.name === 'DoctorEdit'
})

// 表单数据
const form = reactive({
  staffId: '',
  name: '',
  gender: '',
  title: '',
  departmentId: '',
  specialties: [],
  contactInfo: {
    phone: '',
    email: '',
    office: ''
  },
  biography: '',
  education: [],
  certifications: [],
  photo: '',
  status: '在职'
})

// 表单验证规则
const rules = reactive({
  staffId: [formRules.required],
  name: [formRules.required],
  gender: [formRules.required],
  departmentId: [formRules.required],
  'contactInfo.phone': [formRules.phone],
  'contactInfo.email': [formRules.email]
})

// 获取科室列表
const fetchDepartments = async () => {
  try {
    const deptOptions = await getDepartmentOptions();
    
    // 确保每个科室选项都有有效的value和label
    departments.value = deptOptions.map((dept, index) => {
      return {
        ...dept,
        value: dept.value || dept.id || dept.departmentId || String(index + 1),
        label: dept.label || dept.name || `科室${index + 1}`
      };
    });
    
    console.log('获取到科室选项:', departments.value);
  } catch (error) {
    console.error('获取科室列表失败', error);
    ElMessage.error('获取科室列表失败，请刷新页面重试');
    
    // 使用默认科室数据
    departments.value = [
      { value: '1', label: '内科' },
      { value: '2', label: '外科' },
      { value: '3', label: '儿科' },
      { value: '4', label: '妇产科' },
      { value: '5', label: '眼科' },
      { value: '6', label: '口腔科' }
    ];
  }
}

// 获取医生详情
const getDoctorDetails = async (id) => {
  loading.value = true
  try {
    // 确保ID格式正确
    const normalizedId = normalizeId ? normalizeId(id) : id;
    console.log('获取医生详情，使用ID:', normalizedId);
    
    const res = await doctorAPI.getDoctor(normalizedId)
    const doctorData = res.data
    
    console.log('医生详情数据:', doctorData);
    
    // 表单赋值
    for (const key in form) {
      if (key === 'contactInfo') {
        // 对象类型，需要深拷贝
        const contactInfo = doctorData[key] || {};
        form[key] = { ...form[key], ...contactInfo }
      } else {
        // 处理其他字段
        form[key] = doctorData[key] !== undefined ? doctorData[key] : form[key];
      }
    }
    
  } catch (error) {
    console.error('获取医生详情失败', error)
    ElMessage.error('获取医生详情失败')
  } finally {
    loading.value = false
  }
}

// 图片上传前验证
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传头像图片只能是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理头像上传
const handleAvatarUpload = (options) => {
  const file = options.file
  // 这里应该调用实际的文件上传API，此处简化为读取为base64
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    form.photo = reader.result
  }
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 根据后端Schema准备数据
        let formData = { ...form };
        
        if (isEdit.value) {
          // 编辑医生 - 根据DoctorUpdateSchema仅包含可更新字段
          // 删除不允许更新的字段
          const updateData = {
            name: form.name,
            gender: form.gender,
            title: form.title,
            departmentId: form.departmentId,
            specialties: form.specialties,
            contactInfo: form.contactInfo,
            biography: form.biography,
            education: form.education,
            certifications: form.certifications,
            photo: form.photo,
            status: form.status
          };
          
          // 使用规范化的ID
          const doctorId = normalizeId ? normalizeId(route.params.id) : route.params.id;
          console.log('更新医生信息，使用ID:', doctorId);
          console.log('更新数据:', updateData);
          
          await doctorAPI.updateDoctor(doctorId, updateData);
          ElMessage.success('更新医生信息成功');
        } else {
          // 创建医生 - 需要包含staffId等必填字段
          await doctorAPI.createDoctor(formData);
          ElMessage.success('创建医生成功');
        }
        
        // 返回列表页
        goBack();
      } catch (error) {
        console.error(isEdit.value ? '更新失败' : '创建失败', error);
        ElMessage.error(isEdit.value ? '更新医生信息失败' : '创建医生失败');
      } finally {
        loading.value = false;
      }
    }
  });
};

// 返回上一页
const goBack = () => {
  router.push('/doctors/list')
}

// 页面加载时，获取科室列表，如果是编辑模式，获取医生详情
onMounted(() => {
  fetchDepartments()
  
  if (isEdit.value && route.params.id) {
    console.log('编辑模式，获取医生ID:', route.params.id);
    getDoctorDetails(route.params.id)
  }
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-divider {
  margin: 24px 0;
}

.el-divider__text {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
}

.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

</style> 
